package org.itboys.mobile.service.mongo.weixin.cart;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.count.SundayCountDto;
import org.itboys.mobile.dto.count.SundayCountProductDto;
import org.itboys.mobile.entity.mongo.cart.CooCart;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mongo.web.member.SundayMemberService;
import org.itboys.mobile.service.mysql.weixin.product.SundayWeiXinProductService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017/12/7
 * 描述：迈迪龙_微信_购物车
 */
@Service
public class CooWeixinCartService extends BaseMongoService<CooCart>{
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayWeiXinProductService productService;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<CooCart> getEntityClass() {
        return CooCart.class;
    }


    /**
     * 新增购物车（支持批量新增）。
     * @param memberId
     * @param productIds
     * @param nums
     * @param cartType 1,通过购物车加入的；2，通过立即购买加入的
     * @return
     */
    public List<Long> addCart(Long memberId, List<Long> productIds , List<Integer> nums, Integer cartType){

        if(ListUtil.isNull(productIds)|| ListUtil.isNull(nums)||(productIds.size()!=nums.size())){
            throw new ErrorException("传入参数错误");
        }
        //如果是立即购买加入购物车，先删除原来购物车中立即购买加入的数据
        if(cartType== SundayCommonConstants.cart_type_buy_now){
            deleteCart(null,memberId, SundayCommonConstants.cart_type_buy_now);
        }
        //返回结果
        List<Long> cartIds = new ArrayList<Long>();
        //获取要加入的商品
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("ids",productIds);
        List<SundayProduct> products = productService.select(param);
        //旧购物车数据
        param.clear();
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        param.put("cartType",cartType);

        List<CooCart> oldCarts=super.list(param);
        List<CooCart> needToAdd=new ArrayList<CooCart>();

        //比对出哪一些商品是需要新增的，哪一些是增加数量的
        for(int i=0;i< products.size();i++){
            SundayProduct product = products.get(i);
            Integer num =nums.get(i);
            boolean isExist=false;
            for(CooCart oldCart:oldCarts){
                if(oldCart.getProductId().longValue()==product.getId().longValue()){
                    isExist=true;
                    super.update(oldCart.getId(),"num",num+oldCart.getNum());
                    break;
                }
            }
            //本次需要新增的商品
            if(!isExist){
                needToAdd.add(new CooCart(memberId, product.getId(), num,cartType));
            }
        }
        if(ListUtil.isNotNull(needToAdd)){
            super.batchSave(needToAdd);
        }
        for(CooCart needToAd:needToAdd){
            cartIds.add(needToAd.getId());
        }
        return cartIds;

    }


    /**
     * 删除购物车，支持批量删除
     * @param cartIds
     * @param memberId
     * @param cartType
     */
    public void deleteCart(List<Long> cartIds ,Long memberId,Integer cartType){
        Map<String,Object> param = new HashMap<String,Object>();
        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        if(cartType!=null){
            param.put("cartType",cartType);
        }

        super.delete(param);
    }
    /**
     * 获取购物车。不分页。
     * @param memberId
     * @param cartIds 结算/生成订单时传入此参数/手机端合计购物车商品价格（如系统含有满减，x元任选等促销手段）
     * @param cartType 1,通过购物车加入的；2，通过立即购买加入的

     * @return
     */
    public SundayCountDto getCart(Long memberId, List<Long> cartIds, Integer cartType){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("memberId",memberId);
        param.put("isDeleted",0);

        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }
        if(cartType!=null){
            param.put("cartType",cartType);
        }


        List<CooCart> carts = super.list(param);
        //购物车外层数据。总价
        SundayCountDto countDto = new SundayCountDto();
        countDto.setTotalAmount(new BigDecimal("0"));
        countDto.setPayAmount(new BigDecimal("0"));
        countDto.setMemberId(memberId);
        if(ListUtil.isNull(carts))return countDto;
        //对应的商品数据
        List<Long> productIds = new ArrayList<Long>();
        for(CooCart cart:carts){
            productIds.add(cart.getProductId());
        }
        param.clear();
        param.put("ids",productIds);
        List<SundayProduct> products =  productService.select(param);

        //获取当前购物车的类型。1，商城，3商户
        Integer type= null;

        //购物车商品
        List<SundayCountProductDto> countProducts = new ArrayList<SundayCountProductDto>();
        Double totalAmount = 0.00;
        Double payAmount=0.00;
        //零售价
        Double retailAmount=0.00;
        for(CooCart cart:carts){
            for(SundayProduct product:products){
                if(cart.getProductId().longValue()==product.getId().longValue()){
                    SundayCountProductDto countProduct = new
                            SundayCountProductDto(product.getId(), product.getCreateTime(), product.getCreateDate(),
                            cart.getId(), product.getPrice(), product.getName(),product.getNumber(), product.getImage(), product.getStandard(),cart.getNum(),
                            product.getType(),0, product.getStore());
                    totalAmount+=product.getPrice().doubleValue()*cart.getNum();
                    payAmount+=product.getPrice().doubleValue()*cart.getNum();
                  /*  retailAmount+=product.getRetailPrice().doubleValue()*cart.getNum();*/
                    countProducts.add(countProduct);
                    //设置购物车/结算商品类型。便于前端显示钱还是积分
                    type=product.getType();
                    product.setType(type);
                    break;
                }
            }

        }
        countDto.setTotalAmount(new BigDecimal(totalAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
        countDto.setPayAmount(new BigDecimal(payAmount).setScale(2,BigDecimal.ROUND_HALF_UP));

        countDto.setType(type);
        countDto.setProducts(countProducts);

        return countDto;
    }
    /**
     * 修改购物车数量，支持批量修改
     * @param memberId
     * @param cartIds
     * @param nums
     */
    public void updateCart(Long memberId ,List<Long> cartIds ,List<Integer> nums){
        if(ListUtil.isNull(cartIds)||ListUtil.isNull(nums)||(cartIds.size()!=nums.size())){
            throw new ErrorException("传入参数错误");
        }
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("id in",cartIds);
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        List<CooCart> carts = super.list(param);
        for(int i=0;i<carts.size();i++){
            CooCart cart = carts.get(i);
            Integer num = nums.get(i);
            //数量变更后才操作数据库。执行修改
            if(cart.getNum()!=num){
                super.update(cart.getId(),"num",num);
            }
        }
    }
}
